<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

/* @author tubaduc <tubaduc@gmail.com> 
 * @copyright (c) Pyco24
 * @since 26.07.11
 * @version 2.0
 * */
class LoginController extends BaseController {
	private $errorList = array();
	function __construct($registry)
	{
		parent::__construct($registry);
		$this->errorList['username']="";
		$this->errorList['password']="";
	}
	public function get(){
		return $this->registry;
	}
	public function index($user = 0)
	{
		$method = $_SERVER['REQUEST_METHOD'];
		/*if (isset($_SESSION['userid']) || isset($_COOKIE['userid'])) {
			header("Location: ../admincp");
			exit();
		}*/
		if ($this->registry->db->get('userManager')->getCurrentUser()) {
			//var_export($this->registry->db->get('userManager')->getCurrentUser());
			header("Location: ./index");
			//echo($this->registry->db->get('userManager')->getCurrentUser()->get('fbid'));
			exit();
		}
		
		else if ($method=='POST'){
			$username = $_POST['username'];
			$pass = $_POST['password'];
			if (isset($_POST['rememberme'])) {
				$rememberme = $_POST['rememberme'];
			}

			$usermana = $this->registry->db->get('userManager');

			try {
				$usermana->get('username', $username);
				$userlogin = $usermana->authenticate($username, $pass);
				if ($userlogin == null || $userlogin->get('status') == 0) {
					$this->errorList['password'] = "Password isn't correct.";
				}
				else {
					$usermana->login($userlogin);
					//Cookie va Session
					if (isset($rememberme)) {
						if ($rememberme == "on") {
							setcookie('userid',$userlogin->get('uid'),time()+3600);
						}
					}
					header("Location: ./index");
					exit();
				}
			}
			catch (Exception $error) {
				$this->errorList['username'] = "Username isn't correct.<br>";
			};
		}
		$user = $this->registry->db->get('userManager')->getCurrentUser();
        if($user != null){
        	$tags['login'] = '<li id="login"><span> Hello, '. $user->get('username').'</span><a href="{bstoRootPath}logout">Logout</a></li>';	
        }else{
        	$tags['login'] = '<li id="login"><a href="{bstoRootPath}login">Login</a></li>';
        }
		$content = $this->registry->template->getTemplate('login', $this->errorList, 'View');
		echo $content;
	}
}
?>